package com.cl.mypureframe.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.cl.mypureframe.BaseApplication;
import com.cl.mypureframe.R;
import com.cl.mypureframe.util.Log;
import com.cl.mypureframe.util.UtilToast;
import com.cl.mypureframe.util.Utils;
import com.cl.mypureframe.widget.ViewTitle;

import java.util.ArrayList;

import static com.cl.mypureframe.activity.MyWebviewActivity.EXTRA_TITLE;
import static com.cl.mypureframe.activity.MyWebviewActivity.EXTRA_TITLEBAR;
import static com.cl.mypureframe.activity.MyWebviewActivity.EXTRA_URL;

/**
 * @Class: BaseActivity
 * @Description: Activity基类
 * @Author: ChenLei
 * @Date: 2020/11/17---15:04
 */
public class BaseActivity extends FragmentActivity {
    protected final String TAG = getClass().getSimpleName();
    protected ViewTitle viewTitle;
    protected Context aContext;
    private LocalBroadcastManager localBroadcastManager;
    private LocalReceiver localReceiver;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        aContext = this;
    }

    /**
     * 设置标题
     *
     * @param resid 标题文字(e.g., R.string.title)
     */
    protected void setTitleName(int resid) {
        viewTitle = (ViewTitle) findViewById(R.id.titlebar);
        viewTitle.setTitleName(resid);
    }

    /**
     * 设置标题
     *
     * @param name 标题文字(String类型)
     */
    protected void setTitleName(String name) {
        viewTitle = (ViewTitle) findViewById(R.id.titlebar);
        viewTitle.setTitleName(name);
    }

    /**
     * 初始化布局，并且设置标题
     *
     * @param layoutResId Resource ID to be inflated.
     * @param resId       标题文字资源 (e.g., R.string.title)
     */
    protected void initContenView(int layoutResId, int resId) {
        setContentView(layoutResId);
        setTitleName(resId);
    }

    /**
     * 初始化布局(标题栏左侧有返回键，点击关闭)，并且设置标题
     *
     * @param layoutResId Resource ID to be inflated.
     * @param resId       标题文字资源 (e.g., R.string.title)
     */
    protected void initContenViewAndBack(int layoutResId, int resId) {
        setContentView(layoutResId);
        initTitlebarBack(resId);
    }

    /**
     * 设置标题，标题栏左侧有返回键，点击关闭
     *
     * @param resid 标题文字(e.g., R.string.title)
     */
    protected void initTitlebarBack(int resid) {
        viewTitle = (ViewTitle) findViewById(R.id.titlebar);
        viewTitle.setTitleName(resid);
        View ivLeft = viewTitle.activateView(ViewTitle.TitleType.BACK);
        ivLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Utils.hideSoftInput(BaseActivity.this);
                finish();
            }
        });

        TextView tvBack = viewTitle.findViewById(R.id.tv_back);
        tvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Utils.hideSoftInput(BaseActivity.this);
                finish();
            }
        });
    }

    // 标题栏右侧文字
    public void initRightText(String text, View.OnClickListener l) {
        TextView tvRight = (TextView) viewTitle.activateView(ViewTitle.TitleType.RTEXT);
        tvRight.setText(text);
        tvRight.setOnClickListener(l);
    }

    /**
     * 按钮点击事件 在布局文件里设置 android:onClick="onButtonClick"
     *
     * @param view 产生点击事件的View
     */
    public void onButtonClick(View view) {
        Utils.hideSoftInput(this);
        if (view.getId() == R.id.tv_reload) {
            execute();
        }
    }

    protected String getUserId() {
        return BaseApplication.basePreferences.getUserId();
    }

    public void startVerifyActivity(Class<?> cls) {
        startVerifyActivity(cls, new Intent());
    }

    public void startVerifyActivity(Class<?> cls, Intent intent) {
        startActivity(intent.setClass(this, cls));
//        overridePendingTransition(0, 0);// 去掉Activity切换间的动画
    }

    public void startMActivity(Class<?> cls) {
        startActivity(new Intent().setClass(this, cls));
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
    }

    /**
     * 校验 Edittext 是否为空，并返回数据
     *
     * @param resids Edittext 资源ID
     * @return 返回数据； 有空值，则返回空
     */
    protected String[] checkEditTextEmpty(int... resids) {
        int length = resids.length;
        String[] strs = new String[length];
        for (int i = 0; i < length; i++) {
            EditText etName = (EditText) findViewById(resids[i]);
            String name = etName.getText().toString().trim();
            strs[i] = name;
            if (TextUtils.isEmpty(name)) {
                UtilToast.show(R.string.to_notnull);
                strs = null;
                break;
            }

        }
        return strs;
    }

    /**
     * 初始化PopupWindow
     *
     * @param resource ID for an XML layout resource to load (e.g., R.layout.main_page)
     * @return PopupWindow
     */
    protected PopupWindow initPopWindow(int resource) {
        LayoutInflater inflater = LayoutInflater.from(this);
        View pView = inflater.inflate(resource, null);

        PopupWindow pw = new PopupWindow(pView);
        pw.setFocusable(true);
        pw.setOutsideTouchable(true);
        // 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
        pw.setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        pw.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                blurredBackground(1.0f);
            }
        });
        return pw;
    }

    /**
     * 初始化 底部弹出的宽高
     *
     * @param resource ID for an XML layout resource to load (e.g., R.layout.main_page)
     * @return PopupWindow
     */
    protected PopupWindow initPopWindowFromBottom(int resource) {
        PopupWindow pw = initPopWindow(resource);
        pw.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        pw.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        return pw;
    }

    /**
     * 从屏幕底部弹出PopupWindow
     */
    protected void showPwFromBottom(PopupWindow pw) {
        if (pw == null)
            return;
        pw.setAnimationStyle(R.style.PopupAnimation);
        pw.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);

        // 背景变暗
        blurredBackground(0.7f);
    }

    /**
     * 背景变暗
     *
     * @param alpha 0.7f变暗;1.0f回复原状
     */
    protected void blurredBackground(float alpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = alpha;
        getWindow().setAttributes(lp);
    }

    /**
     * 获取屏幕宽高
     *
     * @return int[0] width(宽度);int[1] height(高度)
     */
    protected int[] getDisplayWidthHeight() {
        DisplayMetrics displaymetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        return new int[]{displaymetrics.widthPixels, displaymetrics.heightPixels};
    }

    /**
     * 动态申请权限
     */
    protected void applyPermissions(String... permissions) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> needPermissions = new ArrayList<>();
            for (String aPermission : permissions) {
                if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, aPermission)) {
                    needPermissions.add(aPermission);
                }
            }
            if (needPermissions.isEmpty()) {
                onPermissionSuccess();
            } else {
                final String[] array = needPermissions.toArray(new String[0]);
                ActivityCompat.requestPermissions(this, array, 1);
            }
        } else {
            onPermissionSuccess();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean allGranted = true;
        if (grantResults.length > 0) {
            for (int result : grantResults) {
                if (result == PackageManager.PERMISSION_DENIED) {
                    allGranted = false;
                    break;
                }
            }
            if (allGranted) {
                onPermissionSuccess();
            } else {
                onPermissionDenied();
            }
        } else {
            onPermissionDenied();
            onPermissionDenied();
        }
    }

    /**
     * 动态权限申请 地图定位相关权限
     */
    protected void permissionLocationMap() {
        String[] permissions = new String[]{
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.WRITE_EXTERNAL_STORAGE};
        applyPermissions(permissions);
    }

    /**
     * 权限成功后回调方法
     */
    protected void onPermissionSuccess() {
    }

    /**
     * 权限失败后回调方法
     */
    protected void onPermissionDenied() {
        UtilToast.show(R.string.to_permissondenied);
    }

    @SuppressLint("SetJavaScriptEnabled")
    protected void initWebView(WebView wv, String url) {
        if (!TextUtils.isEmpty(url)) {
            WebSettings settings = wv.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setLoadWithOverviewMode(true);// 适应屏幕
            wv.setWebViewClient(new WebViewClient());
            wv.loadUrl(url);
        }
    }

    @SuppressLint("SetJavaScriptEnabled")
    protected void initWebViewAll(WebView wv, String url) {
        Log.i(TAG, "initWebViewAll:url", url);
        if (!TextUtils.isEmpty(url)) {
            WebSettings settings = wv.getSettings();
            settings.setLoadWithOverviewMode(true);
            settings.setBuiltInZoomControls(true);
            settings.setJavaScriptEnabled(true);
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            settings.setGeolocationEnabled(true);
            settings.setDomStorageEnabled(true);
            settings.setDatabaseEnabled(true);
            settings.setUseWideViewPort(true); // 关键点
            settings.setAllowFileAccess(true); // 允许访问文件
            settings.setPluginState(WebSettings.PluginState.ON);
            settings.setCacheMode(WebSettings.LOAD_NO_CACHE); // 不加载缓存内容
            wv.setWebViewClient(new WebViewClient());
            wv.loadUrl(url);
        }
    }

    protected void startWebviewActivity(String title, String url) {
        Intent intent = new Intent();
        intent.putExtra(EXTRA_TITLE, title);
        intent.putExtra(EXTRA_URL, url);
        startVerifyActivity(MyWebviewActivity.class, intent);
    }

    protected void startWebviewActivity(String url) {
        Intent intent = new Intent();
        intent.putExtra(EXTRA_TITLEBAR, false);
        intent.putExtra(EXTRA_URL, url);
        startVerifyActivity(MyWebviewActivity.class, intent);
    }

    protected int getMColor(int resId) {
        return ContextCompat.getColor(this, resId);
    }

    protected void setVisable(boolean isVisable, int... resid) {
        for (int re : resid) {
            findViewById(re).setVisibility(isVisable ? View.VISIBLE : View.GONE);
        }
    }

    protected void showEmptyView(boolean isShow) {
        setVisable(isShow, R.id.rl_empty);
    }

    protected void execute() {
    }

    // 注册本地广播
    protected void initLocalBroadCast(String action) {
        // 获取实例
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(action);
        localReceiver = new LocalReceiver();
        localBroadcastManager.registerReceiver(localReceiver, intentFilter);
    }

    protected class LocalReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i(TAG, "LocalReceiver", "receive---");
            onReceiveAction(intent);
        }
    }

    protected void onReceiveAction(Intent intent) {
    }

    protected void sendMyBroadcast(String action) {
        Intent intent = new Intent(action);
        sendMyBroadcast(intent);
    }

    protected void sendMyBroadcast(Intent intent) {
        LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
        localBroadcastManager.sendBroadcast(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (localBroadcastManager != null) {
            // 取消注册广播,防止内存泄漏
            localBroadcastManager.unregisterReceiver(localReceiver);
        }
    }

}
